#!/usr/bin/env python
# -*- coding: UTF-8 -*-

# This file is part of emule local client
# 
# The eMule Local Client is free software, you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# eMule Local Client is distributed in the hope that it will be useful
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with eMule Local Client; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

import httplib
import urllib2
import urllib
import cookielib
import re
import os
import cPickle

from constant import *

cookie = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))
urllib2.install_opener(opener)

def login(server, password):
    login_info = (('p', password), ('w', 'password'))
    request = urllib2.Request(server, urllib.urlencode(login_info))
    request.add_header('User-Agent', USER_AGENT)
    return opener.open(request).read()
    
def logout(server, session_id):
    logout_info = (('ses', session_id), ('w', 'logout'))
    request = urllib2.Request(server, urllib.urlencode(logout_info))
    request.add_header('User-Agent', USER_AGENT)
    return opener.open(request).read()

def get_session_id(page_src):
    pattern = '<input type="hidden" name=ses value="(-?\d+)">'
    m = re.search(pattern, page_src)
    return m and m.group(1) or None

def download(server, session_id, ed2k_link):
    download_info = (('ses', session_id), ('w', 'transfer'), ('ed2k', ed2k_link))
    request = urllib2.Request(server, urllib.urlencode(download_info))  
    opener.open(request).read()
    log_download_info(server, session_id, ed2k_link)

def batch_download(server, session_id, links_text):
    links = re.findall('ed2k://\|file\|.+?/', urllib.unquote(links_text))
    task_names = []
    import string
    '''
     '[', ']', '.' seems not recognized by the eXtream mod through web
     so I translate the first two to '(', ')'
     for the consideration of the extension part, '.' not translated
    '''
    for link in links:
        link = link.translate(string.maketrans('[]', '()'))
        link_info = get_ed2k_info(link)
        task_names.append(link_info and link_info[0] or '')
        download(server, session_id, link)

    return task_names

def get_ed2k_info(ed2k_link):
    match = re.match('ed2k://\|file\|(.+?)\|(\d+?)\|(.+?)\|(.*)\|?/', ed2k_link)
    info = [match.group(i) for i in range(1, 5)]
    return match and info or None

def load_download_info(history_file=HISTORY_FILE):
    download_history = []
    if not os.path.exists(history_file):
        dump_download_info(download_history, history_file)
    else:
        download_history = cPickle.load(file(history_file, 'r'))

    return download_history

def dump_download_info(object, history_file=HISTORY_FILE):
    cPickle.dump(object, file(history_file, 'w'))

def log_download_info(server, session_id, ed2k_link, history_file=HISTORY_FILE):
    download_history = load_download_info(history_file)
    link_info = get_ed2k_info(ed2k_link)
    download_info = link_info[:3]
    download_info.append(server)
    download_info.append(session_id)
    import time
    download_info.append(time.strftime('%Y-%m-%d %X', time.localtime(time.time())))
    download_info.append(ed2k_link)

    download_history.append(download_info)
    dump_download_info(download_history, history_file)
